<template>
  <div>
    <el-upload
      ref="upload"
      :action="uploadUrl"
      :before-upload="beforeUpload"
      :on-success="fnUploadSuccess"
      :data="dataExtra"
      :headers="uploadHeaders"
      :http-request="onUpload"
      :disabled="disabled"
      drag
      :auto-upload="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
    >
      <el-button
        slot="trigger"
        size="small"
        type="primary"
      >选取文件</el-button>
      <el-button
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload"
      >上传到服务器</el-button>
      <div
        slot="tip"
        class="el-upload__tip"
      >上传文件大小不能超过 1G</div>
    </el-upload>
  </div>
</template>
<script>
import { ossStsAuthent } from '@/api/attach'
import { generateUploadFileName } from '@/utils'
import OSS from 'ali-oss'
export default {
  name: 'FileUpload',
  props: {
    accept: {
      type: [Array, String],
      default: 'video/mp4'
    }
  },
  data() {
    return {
      dataExtra: null,
      uploadUrl: '',
      fileList: [],
      uploadHeaders: {
        authorization: '',
        'Access-Control-Allow-Origin': '*'
      },
      disabled: false
    }
  },
  computed: {
    acceptData() {
      var accepts = this.accept
      if (Array.isArray) {
        if (Array.isArray(accepts)) {
          return accepts.join(', ')
        }
      } else if (accepts instanceof Array) {
        return accepts.join(', ')
      }
      return accepts
    }
  },
  methods: {
    beforeUpload(dd) {
      console.log('video beforeUpload', dd)
      // const _self = this
      // return new Promise((resolve, reject) => {
      //   _self._data.headers['Access-Control-Allow-Origin'] = '*'
      //   resolve(true)
      // })
    },
    submitUpload() {
      console.log('video submitUpload')
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log('video handleRemove', file, fileList)
    },
    handlePreview(file) {
      console.log('video handlePreview', file)
    },
    /**
     * @description [onUpload 覆盖默认的上传行为，实现自定义上传]
     * @author   shanshuizinong
     * @param    {object}   option [上传选项]
     * @return   {null}   [没有返回]
     */
    async onUpload(option) {
      console.log('onUpload', option)
      try {
        const vm = this
        vm.disabled = true
        // 获取OSS配置信息
        const ret = await ossStsAuthent()
        if (!(ret.code === 200 && ret.data)) {
          console.log('restttttttttttttt', ret)
          throw new Error('获取OSS参数失败')
        }
        const ossData = ret.data
        // const relativePath = ossData.relativePath
        const date = vm.$moment().format('YYYYMM/DD')
        const relativePath = 'attachments/sts/' + date + '/'
        const client = new OSS({
          // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
          region: 'oss-cn-hangzhou',
          // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
          accessKeyId: ossData.AccessKeyId,
          accessKeySecret: ossData.AccessKeySecret,
          // 填写Bucket名称，例如examplebucket。
          bucket: ossData.bucket,
          stsToken: ossData.SecurityToken
        })

        const file = option.file

        const point = file.name.lastIndexOf('.')
        const suffix = file.name.substr(point)
        const fileNames = generateUploadFileName(suffix)
        const uploadOptions = {
          progress: async function(p) {
            const e = {}
            e.percent = p * 100
            option.onProgress(e)
          },
          partSize: 500 * 1024,
          timeout: 60000,
          headers: {
            'Access-Control-Allow-Origin': '*'
          }
        }
        // 分片上传文件
        const result = await client.multipartUpload(
          relativePath + fileNames,
          file,
          uploadOptions
        )
        console.log('upload', result)
        if (result.res.statusCode === 200) {
          // option.onSuccess(ret)
          return result
        } else {
          vm.disabled = false
          option.onError('上传失败')
        }
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    /**
     * @description [fnUploadSuccess 文件上传成功的函数]
     * @author   shanshuizinong
     * @return   {null}  [没有返回]
     */
    async fnUploadSuccess(dd) {
      console.log('success', dd)
    }
  }
}
</script>

